package controller;

import dao.ArticleDao;
import model.Article;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintWriter;

public class ArticleDetailApiServlet extends HttpServlet {
    private ArticleDao dao = new ArticleDao();
    private Gson gson = new Gson();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        
        try {
            String idStr = request.getParameter("id");
            if (idStr == null || idStr.trim().isEmpty()) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                PrintWriter out = response.getWriter();
                out.print("{\"error\":\"缺少文章ID参数\"}");
                out.flush();
                return;
            }
            
            int id = Integer.parseInt(idStr);
            Article article = dao.getArticleById(id);
            
            if (article == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                PrintWriter out = response.getWriter();
                out.print("{\"error\":\"文章不存在\"}");
                out.flush();
                return;
            }
            
            String json = gson.toJson(article);
            PrintWriter out = response.getWriter();
            out.print(json);
            out.flush();
            
        } catch (NumberFormatException e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            PrintWriter out = response.getWriter();
            out.print("{\"error\":\"无效的文章ID格式\"}");
            out.flush();
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            PrintWriter out = response.getWriter();
            out.print("{\"error\":\"服务器内部错误\"}");
            out.flush();
        }
    }
}